#!/bin/bash
BASE_DIR=`cd $(dirname $(dirname $0)); pwd`
INNOEXTRACT_BIN=${BASE_DIR}/tools/innoextract
TMP_DIR=${BASE_DIR}/temp
APP_DIR=${TMP_DIR}/app
DAT=qqwry_latest.dat

function log(){
    echo -n $(date +"[%Y-%m-%d %H:%M:%S]") $1
}

function check_success(){
    if [ $1 -eq 0 ]; then
        echo "ok"
    else
        echo "failed"
        exit $1
    fi
}


echo ====================BEGIN====================

if [ ! -d "${TMP_DIR}" ]; then
    mkdir -p ${TMP_DIR}
fi

log "Downloading..."
wget -qO ${TMP_DIR}/setup.zip http://update.cz88.net/soft/setup.zip 2>/dev/null
check_success $?

log "Unzip..."
cd ${TMP_DIR} && unzip -oqq setup.zip
check_success $?

log "Extract files..."
${INNOEXTRACT_BIN} -qs ${TMP_DIR}/setup.exe
check_success $?

log "Get old hash..."
oldmd5=$(md5sum -b ${BASE_DIR}/${DAT} | cut -f 1 -d ' ')
check_success $?

log "Calc new hash..."
newmd5=$(md5sum -b ${APP_DIR}/qqwry.dat | cut -f 1 -d ' ')
check_success $?

log "Compare old qqwry.dat..."
if [ "${oldmd5}" = "${newmd5}" ]; then
    echo "no update."
else
    cp -f ${APP_DIR}/qqwry.dat ${BASE_DIR}/qqwry_latest.dat
    check_success $?

    if [ "$(git diff --name-only ${DAT} | wc -l)" -eq "1" ]; then
        log "Push to gitee.com..."
        git add ${DAT}
        git commit -qm "Auto Update"
        git tag $(date +"%Y%m%d")
        git push --all --tags -q -u origin master >/dev/null 2>&1
        check_success $?
    fi
fi

log "Clearing..."
rm ${TMP_DIR} -fr
check_success $?
echo ====================END====================
echo

